const logger = require('../utils/logger');

const errorHandler = (err, req, res, next) => {
  logger.error('Error occurred:', {
    error: err.message,
    stack: err.stack,
    path: req.path,
    method: req.method
  });

  // 数据库连接错误
  if (err.code === 'ETIMEDOUT' || err.code === 'ECONNREFUSED') {
    return res.status(500).json({
      success: false,
      error: '数据库连接失败，请稍后重试',
      code: 500
    });
  }

  // 默认错误响应
  res.status(500).json({
    success: false,
    error: process.env.NODE_ENV === 'production' ? '服务器内部错误' : err.message,
    code: 500
  });
};

module.exports = errorHandler; 